﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Sunboxsoft.Bases.Web.Models
{
    public class Menu : ICloneable
    {
        /// <summary>
        /// 资源编码
        /// </summary>
        public string ResourceCode { get; set; }
        public string IconUrl { get; set; }
        public string Icon { get; set; }
        public string Text { get; set; }
        public string LinkUrl { get; set; }

        public List<Menu> Children { get; set; }

        public bool IsFolder { get; set; }
        public bool IsOpened { get; set; }
        public bool IsActived { get; set; }

        /// <summary>
        /// url正则匹配规则数组，符合这个规则话就激活这个菜单
        /// </summary>
        public string[] UrlRegexArrage { get; set; }

        public Menu()
        {
            Icon = "icon-file";
        }

        public object Clone()
        {
            Menu clone = new Menu();
            clone.ResourceCode = this.ResourceCode;
            clone.IconUrl = this.IconUrl;
            clone.Icon = this.Icon;
            clone.Text = this.Text;
            clone.LinkUrl = this.LinkUrl;
            //if(this.Children!=null)
            //{
            //    clone.Children = new List<Menu>();
            //    for (int index = 0; index < this.Children.Count; index++)
            //    {
            //        clone.Children.Add(this.Children[index].Clone() as Menu);
            //    }
            //}
            clone.IsFolder = this.IsFolder;
            clone.IsOpened = this.IsOpened;
            clone.IsActived = this.IsActived;
            clone.UrlRegexArrage = this.UrlRegexArrage;

            return clone;
        }
    }

    public class MenuResolver
    {
        public static string BaseUrl = System.Configuration.ConfigurationManager.AppSettings["BaseUrl"];

        public static List<Menu> Resolve(List<Menu> menus, Uri currentUrl)
        {
            bool hasActiveChild;
            foreach (var menu in menus)
            {
                if (menu.Children != null && menu.Children.Count > 0)
                {
                    OnTreeMenuTree(menu, currentUrl, out hasActiveChild);
                }
                else
                {
                    OnSingleMenuTree(menu, currentUrl, out hasActiveChild);
                }
            }

            return menus;
        }

        private static void OnSingleMenuTree(Models.Menu menu, Uri currentUrl, out bool hasActiveChild)
        {
            if (IsSameUrl(menu.LinkUrl, currentUrl) || IsMatchUrl(menu, currentUrl))
            {
                hasActiveChild = true;
                menu.IsActived = true;
            }
            else
            {
                menu.LinkUrl = GetAbsoluteUrl(menu.LinkUrl);
                hasActiveChild = false;
                menu.IsActived = false;
            }
        }

        private static void OnTreeMenuTree(Models.Menu menu, Uri currentUrl, out bool hasActiveChild)
        {
            menu.IsFolder = true;
            hasActiveChild = false;
            bool isActiveOnThisOne = false;
            if (IsSameUrl(menu.LinkUrl, currentUrl))
            {
                isActiveOnThisOne = true;
            }
            else
            {
                isActiveOnThisOne = false;
            }

            StringBuilder childrenHtmlBuilder = new StringBuilder();
            foreach (var subMenu in menu.Children)
            {
                bool hasActiveChildInThis = false;
                if (subMenu.Children != null && subMenu.Children.Count > 0)
                {
                    OnTreeMenuTree(subMenu, currentUrl, out hasActiveChildInThis);
                }
                else
                {
                    OnSingleMenuTree(subMenu, currentUrl, out hasActiveChildInThis);
                }

                if (hasActiveChildInThis)
                {
                    // 有子项目是active的
                    hasActiveChild = true;
                }
            }

            if (hasActiveChild)
            {
                menu.IsOpened = true;
            }
            else if (isActiveOnThisOne)
            {
                hasActiveChild = true;
                menu.IsActived = true;
            }
            else
            {
                hasActiveChild = false;
            }
        }

        private static bool IsSameUrl(string url1, Uri url2)
        {
            if (string.IsNullOrEmpty(url1))
            {
                return false;
            }
            if(string.Equals(url1, "#"))
            {
                return false;
            }

            Uri actualUrl1;
            if (Uri.TryCreate(new Uri(BaseUrl), url1, out actualUrl1) == false)
            {
                return false;
            }
            if (string.Equals(actualUrl1.LocalPath, url2.LocalPath, StringComparison.CurrentCultureIgnoreCase))
            {
                return true;
            }
            return false;
        }

        private static bool IsMatchUrl(Menu menu, Uri url)
        {
            if (menu.UrlRegexArrage != null && menu.UrlRegexArrage.Length > 0)
            {
                foreach (string urlRegexString in menu.UrlRegexArrage)
                {
                    Regex regex = new Regex(urlRegexString, RegexOptions.IgnoreCase);
                    if (regex.IsMatch(url.ToString()))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private static string GetAbsoluteUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                return string.Empty;
            }

            Uri actualUrl;
            if (Uri.TryCreate(new Uri(BaseUrl), url, out actualUrl))
            {
                return actualUrl.ToString();
            }
            return url;
        }
    }
}
